package com.buttonpay.home;

import java.text.DecimalFormat;

import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast; 
import com.buttonpay.AppData;
import com.buttonpay.HttpConn;
import com.buttonpay.MD5Generator;
import com.buttonpay.R;

public class BusinessSummaryActivity extends Activity
{
	ListView listSummary;
	Button btnBack,btnLogout;
	String startDate,endDate;
	ProgressDialog pd= null;
	Handler handler= new Handler();
	MD5Generator md5Generator=new MD5Generator();
	HttpConn httpConn=new HttpConn();
	String URL;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.transaction_list);
		Bundle bundle=getIntent().getExtras();
		startDate=bundle.getString("startDate");
		endDate=bundle.getString("endDate");
		System.out.println("Start Date==>"+startDate+"\n"
				+"End date===>"+endDate);
		btnBack=(Button)findViewById(R.id.btnPrevious);
        btnLogout=(Button)findViewById(R.id.btnLogout);
        listSummary=(ListView)findViewById(R.id.list_transactionList);
        ((TextView)findViewById(R.id.tv_headerText)).setText("Business Summary");
        
        pd=ProgressDialog.show(BusinessSummaryActivity.this,"please wait.",null);
        pd.setCancelable(true);
        
        pd.setContentView(R.layout.progress);
        new Thread(getSummary).start();
        
        btnBack.setOnClickListener(new OnClickListener()
		{
			
			public void onClick(View arg0) 
			{
				// TODO Auto-generated method stub
				finish();
			}
			
		});
		
		btnLogout.setOnClickListener(new OnClickListener()
		{
			
			public void onClick(View v) 
			{
				new AlertDialog.Builder(BusinessSummaryActivity.this)
		        .setTitle( "Exit Application" )
		        .setMessage( "Are you sure you want to Logout?" )
		        .setPositiveButton("YES", new android.content.DialogInterface.OnClickListener() 
		        {
		            public void onClick(DialogInterface arg0, int arg1) 
		            {
		                setResult(2);
		            	finish();
		            }

					public void onClick(View v) 
					{
						// TODO Auto-generated method stub 
					}
		        })
		        .setNegativeButton("NO",  new android.content.DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface arg0, int arg1)
		            {
		                //do stuff onclick of CANCEL
		            	arg0.dismiss(); 
		            }
		            
		            public void onClick(View v) 
					{
						// TODO Auto-generated method stub
					}
		        }).show();
			}
		});
		
	}
	double roundTwoDecimals(double d) {
		DecimalFormat twoDForm = new DecimalFormat("#.##");
		return Double.valueOf(twoDForm.format(d));
	}

	Runnable getSummary=new Runnable()
	{
		
		public void run() 
		{
			try
			{
				String checksum=md5Generator.MD5(md5Generator.SHA1(AppData.getUserInfo().getLoginID()+"|"+startDate+"|"+endDate+"|"+
				AppData.getUserInfo().getpublickey()));
				URL=AppData.hostURL+"/WebService/iTopUp/agentapp.php/ResellerBalanceDetail/LoginId/"+AppData.getUserInfo().getLoginID()+
				"/StartTime/"+startDate+"/EndTime/"+endDate+"/Checksum/"+checksum;
				 String response=httpConn.createHttpConn(URL);
				 System.out.println("Response:"+response); 
				 
				 final JSONObject jsonObject=new JSONObject(response);
				 double opBal,credits,sales,comm,cloBalance;
				 if(jsonObject.getString("ResponseCode").equals("000")&&jsonObject.getString("ResponseDescription").equals("Successfull"))
				 {
					 
					 opBal=roundTwoDecimals(Double.parseDouble(jsonObject.getString("OpeningBalance"))/100);
					 credits=roundTwoDecimals(Double.parseDouble(jsonObject.getString("PaymentCredits"))/100);
					 sales=roundTwoDecimals(Double.parseDouble(jsonObject.getString("Sales"))/100);
					 comm=roundTwoDecimals(Double.parseDouble(jsonObject.getString("Commission"))/100);
					 cloBalance=roundTwoDecimals(Double.parseDouble(jsonObject.getString("ClosingBalance"))/100);
					 
					 
					 final String header[]=new String[]{"Opening Balance","Payment Credits","Sales","Commision","Closing Balance"};
					 final String values[]=new String[]{""+opBal,""+credits,""+sales,""+comm,""+cloBalance};
					 
					 handler.post(new Runnable() 
					 {
						
						public void run() 
						{
							// TODO Auto-generated method stub
							lnfo_adapter adapter=new lnfo_adapter(BusinessSummaryActivity.this, header, values);
							listSummary.setAdapter(adapter);
							pd.dismiss();
						}
					});
					 
				 }
				 else
				 {
					handler.post(new Runnable()
					{
						
						public void run() 
						{
							// TODO Auto-generated method stub
							pd.dismiss();
							try 
							{
								Toast.makeText(BusinessSummaryActivity.this,jsonObject.getString("ResponseDescription"),Toast.LENGTH_LONG).show();
								finish();
							}
							catch (JSONException e) 
							{
								e.printStackTrace();
							}
						}
					});
				 } 
			}
 			catch(final Exception e)
 			{
 				handler.post(new Runnable()
				{ 
					public void run() 
					{
						pd.dismiss();
						
						Toast.makeText(BusinessSummaryActivity.this,e.getMessage(),Toast.LENGTH_LONG).show();
					}
				});
 			}
			
		}
	};
	
    class Viewholder
	{
		TextView txtHeader;
		TextView txtValue;
	}
    class lnfo_adapter extends BaseAdapter
	{

		Activity context;
		String header[];
		String values[];
		
		public lnfo_adapter(Activity context, String[] header,
				String[] values) 
		{
			this.context=context;
			this.header=header;
			this.values=values;
		}

		public int getCount() {
			// TODO Auto-generated method stub
			return header.length;
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		
		public View getView(int position, View convertView, ViewGroup parent) 
		{
			// TODO Auto-generated method stub
			Viewholder holder;
			LayoutInflater inflater=context.getLayoutInflater();
			
			if(convertView==null)
			{
				convertView=inflater.inflate(R.layout.lv_info_row, null);
				holder=new Viewholder();
				holder.txtHeader=(TextView)convertView.findViewById(R.id.txtname);
				holder.txtValue=(TextView)convertView.findViewById(R.id.txtvalue);
				convertView.setTag(holder);
			}
			else
			{
				holder=(Viewholder)convertView.getTag();
			}
			
			holder.txtHeader.setText(header[position]);
			holder.txtValue.setText(values[position]);
			
			return convertView;
		}

	}

}
